<?php


namespace app\admin\controller\system;


use app\admin\model\SystemAdmin;
use app\admin\model\SystemErrorLog;
use app\admin\model\UserBase;
use app\admin\service\TriggerService;
use app\admin\traits\Curd;
use app\common\constants\AdminConstant;
use app\common\controller\AdminController;
use app\common\service\redis\RedisQueueService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Session;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="管理员管理")
 */
class Admin extends AdminController
{

    use Curd;

    protected $sort = [
        'sort' => 'desc',
        'id' => 'desc',
    ];

    protected $allowModifyFields = [
        'sort', 'remark', 'phone', 'status'
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SystemAdmin();
        $this->assign('auth_list', $this->model->getAuthList());
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParams();
            $permission_ids = session('admin_ids');
            $count = $this->model
                ->where($where)
                ->withJoin(['branch'], 'LEFT')
                ->whereIn('id', $permission_ids)
                ->count();
            $list = $this->model
                ->withoutField('password')
                ->where($where)
                ->withJoin([
                    'branch' => ['branch_id', 'name']
                ], 'LEFT')
                ->whereIn('id', $permission_ids)//仅显示自己和下级管理员
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $authIds = $this->request->post('auth_ids', []);
            $post['auth_ids'] = implode(',', array_keys($authIds));
            $rule = [
                'username' => 'unique:systemAdmin',
                'password' => 'require|confirm',
//                'phone'      => 'unique:systemAdmin',
            ];
            $message = [
                'username.unique' => '管理员名禁止重复',
                'password.require' => '请输入密码',
                'password.confirm' => '两次输入密码必须一致',
            ];
            $this->validate($post, $rule, $message);
            $re = $this->model->checkPid($post);
            if (!$re['status']) {
                $this->error($re['msg']);
            }
            try {
                $save = $this->model->save($re['data']);
            } catch (\Exception $e) {
                SystemErrorLog::init()->addError($e->getMessage());
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $authIds = $this->request->post('auth_ids', []);
            $post['auth_ids'] = implode(',', array_keys($authIds));
            $rule = [];
            $this->validate($post, $rule);
            if (isset($row['password'])) {
                unset($row['password']);
            }
            $re = $this->model->checkPid($post);
            if (!$re['status']) {
                $this->error($re['msg']);
            }
            try {
                $save = $row->save($re['data']);
                //如果有绑定会员操作
                UserBase::init()->bindAdmin($re['data']['bind_user'], $id);
                TriggerService::updateMenu($id);
            } catch (\Exception $e) {
                SystemErrorLog::init()->addError($e->getMessage());
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $row->auth_ids = explode(',', $row->auth_ids);
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="设置密码")
     */
    public function password($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'password|登录密码' => 'require',
                'password_again|确认密码' => 'require',
            ];
            $this->validate($post, $rule);
            if ($post['password'] != $post['password_again']) {
                $this->error('两次密码输入不一致');
            }
            try {
                $save = $row->save([
                    'password' => password($post['password']),
                ]);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $row->auth_ids = explode(',', $row->auth_ids);
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        $id == AdminConstant::SUPER_ADMIN_ID && $this->error('超级管理员不允许修改');
        if (is_array($id)) {
            if (in_array(AdminConstant::SUPER_ADMIN_ID, $id)) {
                $this->error('超级管理员不允许修改');
            }
        }
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID' => 'require',
            'field|字段' => 'require',
            'value|值' => 'require',
        ];
        $this->validate($post, $rule);
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        if ($post['id'] == AdminConstant::SUPER_ADMIN_ID && $post['field'] == 'status') {
            $this->error('超级管理员状态不允许修改');
        }
        $row = $this->model->find($post['id']);
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

    /**
     * @NodeAnotation(title="聊天")
     */
    public function chat()
    {
        $admin = session('admin');
        $admin_info = [
            'id' => $admin['id'],
            'username' => $admin['username'],
            'head_img' => $admin['head_img'],
        ];
        return $this->fetch('', ['admin_info' => json_encode($admin_info)]);
    }

    public function get_team()
    {
//        $team_ids = session('admin_ids');
        $map = ['id' => session('admin_ids')];
        $admins = $this->model->where($map)->field(['id', 'remark'])->select();
        $this->success(null, $admins);
    }


}
